package com.manage.modules.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.manage.common.config.RuoYiConfig;
import com.manage.common.core.domain.entity.SysUser;
import com.manage.framework.config.ServerConfig;
import com.manage.modules.domain.TBaseFaultPhoto;
import com.manage.modules.domain.TBaseRepairPhoto;
import com.manage.modules.dto.TBaseFaultSelectDto;
import com.manage.modules.dto.TBaseFaultSelectReturnDto;
import com.manage.modules.service.ITBaseFaultService;
import com.manage.modules.service.ITBaseRepairPhotoService;
import com.manage.modules.utils.UploadUtil;
import com.manage.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.manage.modules.bo.TBaseRepairAddBo;
import com.manage.modules.bo.TBaseRepairQueryBo;
import com.manage.modules.bo.TBaseRepairEditBo;
import com.manage.modules.domain.TBaseRepair;
import com.manage.modules.mapper.TBaseRepairMapper;
import com.manage.modules.vo.TBaseRepairVo;
import com.manage.modules.service.ITBaseRepairService;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 维修单管理Service业务层处理
 *
 * @author wx
 * @date 2021-09-09
 */
@Service
public class TBaseRepairServiceImpl extends ServiceImpl<TBaseRepairMapper, TBaseRepair> implements ITBaseRepairService {
    @Resource
    private ITBaseFaultService faultService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ServerConfig serverConfig;
    @Resource
    private ITBaseRepairPhotoService repairPhotoService;

    @Override
    public TBaseRepairVo queryById(Long repairId) {
        TBaseRepair db = this.baseMapper.selectById(repairId);
        // 取出所有照片
        List<TBaseRepairPhoto> photoList = repairPhotoService.findByRepairId(repairId);
        // 加上路径
        for (TBaseRepairPhoto repairPhoto : photoList) {
            repairPhoto.setUrl(serverConfig.getUrl() + repairPhoto.getUrl());
            repairPhoto.setLocal(RuoYiConfig.getProfile() + repairPhoto.getLocal());
        }
        TBaseRepairVo repairVo = BeanUtil.toBean(db, TBaseRepairVo.class);
        repairVo.setTBaseRepairPhotoList(photoList);
        return repairVo;
    }

    @Override
    public List<TBaseRepairVo> queryList(TBaseRepairQueryBo bo) {
        LambdaQueryWrapper<TBaseRepair> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getStationIdC()), TBaseRepair::getStationIdC, bo.getStationIdC());
        lqw.eq(bo.getEquipHistoryId() != null, TBaseRepair::getEquipHistoryId, bo.getEquipHistoryId());
        lqw.eq(StrUtil.isNotBlank(bo.getRepairCode()), TBaseRepair::getRepairCode, bo.getRepairCode());
        lqw.ge(bo.getRepairStartTime() != null, TBaseRepair::getRepairStartTime, bo.getRepairStartTime());
        lqw.le(bo.getRepairEndTime() != null, TBaseRepair::getRepairEndTime, bo.getRepairEndTime());
        lqw.eq(bo.getRepairTypeId() != null, TBaseRepair::getRepairTypeId, bo.getRepairTypeId());
        lqw.eq(bo.getRepairState() != null, TBaseRepair::getRepairState, bo.getRepairState());
        List<TBaseRepairVo> repairVos = entity2Vo(this.list(lqw));
        List<TBaseFaultSelectReturnDto> dtoList = faultService.queryBySelectDto(new TBaseFaultSelectDto());
        List<SysUser> userList = sysUserService.listIdAndNickname();
        for (TBaseRepairVo repairVo : repairVos) {
            // 遍历 当故障ID相等时 获取故障编号
            for (TBaseFaultSelectReturnDto returnDto : dtoList) {
                if(returnDto.getFaultId().equals(repairVo.getFaultId())){
                    repairVo.setFaultCode(returnDto.getFaultCode());
                }
            }
            // 设置值班用户昵称
            repairVo.setDutyUserName(sysUserService.getNickNameByUserId(repairVo.getDutyUserId(),userList));
            // 设置维修用户昵称
            repairVo.setRepairUserName(sysUserService.getNickNameByUserId(repairVo.getRepairUserId(),userList));
        }
        return repairVos;
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<TBaseRepairVo> entity2Vo(Collection<TBaseRepair> collection) {
        List<TBaseRepairVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, TBaseRepairVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<TBaseRepair> page = (Page<TBaseRepair>) collection;
            Page<TBaseRepairVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(TBaseRepairAddBo bo) {
        TBaseRepair add = BeanUtil.toBean(bo, TBaseRepair.class);
        validEntityBeforeSave(add);
        this.save(add);

        List<TBaseRepairPhoto> sitePhotoUrlList = bo.getSitePhotoUrlList();
        // 只存相对路径
        setUrl(sitePhotoUrlList, add.getRepairId());

        // 保存新增的
        repairPhotoService.saveBatch(sitePhotoUrlList);
        // 删除不要的
        repairPhotoService.delete(bo.getDeletePhotoList());

        return true;
    }

    @Override
    public Boolean updateByEditBo(TBaseRepairEditBo bo) {
        TBaseRepair update = BeanUtil.toBean(bo, TBaseRepair.class);
        validEntityBeforeSave(update);

        List<TBaseRepairPhoto> sitePhotoUrlList = bo.getSitePhotoUrlList();
        // 只存相对路径
        setUrl(sitePhotoUrlList, update.getRepairId());

        // 保存或修改新增的
        repairPhotoService.saveOrUpdateBatch(sitePhotoUrlList);
        // 删除不要的
        repairPhotoService.delete(bo.getDeletePhotoList());
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TBaseRepair entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    /**
     * 路径修正
     */
    private void setUrl(List<TBaseRepairPhoto> tBaseRepairPhotoList, Long repairId) {
        // 只存相对路径
        for (TBaseRepairPhoto tBaseRepairPhoto : tBaseRepairPhotoList) {
            tBaseRepairPhoto.setRepairId(repairId);
            tBaseRepairPhoto.setUrl(UploadUtil.getUrlByDelete(tBaseRepairPhoto.getUrl(), serverConfig.getUrl()));
            tBaseRepairPhoto.setLocal(UploadUtil.getUrlByDelete(tBaseRepairPhoto.getLocal(), RuoYiConfig.getProfile()));
        }
    }
}
